<?php
require_once '/Workerman/Autoloader.php';
use Workerman\Worker;
use Workerman\Lib\Timer;
use Workerman\Channel\Client;
use Workerman\Lib\MySQL as Db;
require_once 'common.php';

// 连接验证失效时间
define('LOGIN_TIME', 5);

// websocket服务端
$worker = new Worker('websocket://0.0.0.0:4236');
$worker->count=2;
$worker->name = 'pusher';

function publish($worker) {
    // Channel客户端连接到Channel服务端
    Client::connect("sub.nao.com", 2206);

    // 以自己的进程id为事件名称 订阅worker->id事件并注册事件处理函数
    Client::on($worker->id, function($event_data) use ($worker) {
        $to_connection_id = $event_data['to_connection_id'];
        if(!isset($worker->connections[$to_connection_id])) {
            return E(NULL, "转发连接已经不存在");
        }
        $to_connection = $worker->connections[$to_connection_id];
        E($to_connection, "转发内容: ".$event_data['data']);
        $to_connection->send($event_data['data']);
    });

    // 收到广播事件后向当前进程内所有客户端连接发送广播数据
    Client::on('广播', function($event_data) use ($worker) {
        E(NULL, "广播内容: ".$event_data['data']);
        foreach($worker->connections as $connection) {
            $connection->send($event_data['data']);
        }
    });
}

function login($connection, $data) {
    E($connection, "$data 登录验证中...");
    $rs = query('proc_user_queryByCode', array($data));
    if ($rs) {
        Timer::del($connection->timer_id);
        $rs = $rs[0];
        $rs['worker_id'] = $connection->worker->id;
        $rs['connection_id'] = $connection->id;
        $rs['userkey'] = $data;

        $connection->redis->hMSet($rs['user_uuid'], $rs);
        $connection->user = $rs;
        $connection->send(encode('login', 'ok'));

        E($connection, "登录验证成功, 登录信息如下: \n".var_export($rs, true));
    } else {
        $connection->close(encode('login', 'fail'));
    }
}

function chat($connection, $data) {
    $connection->send(encode('chat', $data));
}

function ping($connection, $data) {
    E($connection, "报到 ".++$connection->pingNum." 次");
}

$worker->onWorkerStart = function($worker) {
    try {
        publish($worker);
        $worker->redis = new Redis();
        $worker->redis->connect('redis.nao.com', 6379);
    } catch (Exception $e) {
        E(NULL, "WorkerStart错误: ".$e->getMessage());
    }
};

$worker->onConnect = function($connection) use ($worker) {
    E($connection, "连接成功");

    $connection->worker_id = $worker->id;
    $connection->redis = $worker->redis;
    $connection->pingNum = 0;

    $connection->timer_id = Timer::add(LOGIN_TIME, function() use ($connection) {
        E($connection, "连接验证超时");
        $connection->close(encode('error', '连接验证超时'));
    });
};

$worker->onMessage = function($connection, $data) {
    try {
        $data = json_decode($data, true);
        call_user_func_array($data['type'],
                             [$connection, $data['data']]);
    } catch (Exception $e) {
        E($connection, "异常信息: ".$e->getMessage());
        $connection->send(encode('error', $e->getMessage()));
    }
};

$worker->onClose = function($connection) {
    E($connection, "断开连接, 正在执行onClose...");
    isset($connection->user['user_uuid']) && $connection->redis->delete($connection->user['user_uuid']);
    isset($connection->timer_id) && Timer::del($connection->timer_id);
};

// Worker::$stdoutFile = './workerman.log';
// Worker::$daemonize = true;

Worker::runAll();

